﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.IO;
using Finance.Data.Entities;
using Finance.TodoSoft.Data.CompactSql;
using TodoSoft.Data;
using TodoSoft.Data.Migration;

namespace Finance.Data
{
	internal class FinanceDataBase : DataBase, IDataBase, IFinanceDataBase
	{
		public IContractors Contractors { get; private set; }
		public IDocuments Documents { get; private set; }
		public IDebtDocuments DebtDocuments { get; private set; }
		public IRepayDebtDocuments RepayDebtDocuments { get; private set; }
		public DocumentSubTypes DocumentSubTypes { get; private set; }
		public INotes Notes { get; private set; }
		public IProducts Products { get; private set; }

		readonly DocumentType[] _documentTypes = new []
			{
				DocumentType.Dohod, DocumentType.DohodZaim, DocumentType.DohodZaimBack, 
				DocumentType.Rashod, DocumentType.RashodZaim, DocumentType.RashodZaimBack, 
			};

		public IEnumerable<DocumentType> DocumentTypes
		{
			get { return _documentTypes; }
		}

		public FinanceDataBase() : base(SqlCeProviderFactory.Instance)
		{
		}

		
		public override void OpenConnection(string dataBaseFullPath)
		{
			var connectionString = "Data Source=" + dataBaseFullPath;
			
			var dbFileInfo = new FileInfo(dataBaseFullPath);
			if (!dbFileInfo.Exists)
			{
				if(!dbFileInfo.Directory.Exists)
					dbFileInfo.Directory.Create();

				var engine = new SqlCeEngine(connectionString);
                engine.CreateDatabase();
			}

			base.OpenConnection(connectionString);
			Sql = new CompactSqlCommandProcessor(Connection);

			//Update database structure
			var dbMigrator = new Migrator(new[]{typeof(FinanceDataBaseMigration)});
			dbMigrator.Migrate(this);
            
			//Initialize data repositories
			Documents = new Documents(this);
		    DocumentSubTypes = new DocumentSubTypes(this);
			DocumentSubTypes.Update();

			DebtDocuments = new DebtDocuments(this);
			RepayDebtDocuments = new RepayDebtDocuments(this);

			Notes = new Notes(this);
			Contractors = new Contractors(this);

			Products = new Products(this);
		}
        
		public ISqlCommandProcessor OpenCommandProcessor()
		{
			return new CompactSqlCommandProcessor(Connection);
		}
	}
}
